import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/toolkit/utilities/app_constants.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/common_utils.dart';
import 'package:thal/backstage/toolkit/widgets/loading_indicator.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';

part 'register_production.page.dart';

/// 注册页面
@PagePath('/register')
class RegisterProduction extends StatefulWidget {
  const RegisterProduction({super.key});

  @pageRouteQuery
  static const query = _$RegisterProductionQuery();

  @override
  State<RegisterProduction> createState() => _RegisterProductionState();
}

class _RegisterProductionState extends State<RegisterProduction> {
  final _accountNameInput = TextEditingController();
  final _securePasswordInput = TextEditingController();

  @override
  void dispose() {
    _accountNameInput.dispose();
    _securePasswordInput.dispose();
    super.dispose();
  }

  /// 处理注册逻辑
  Future<void> _establishAccount() async {
    final name = _accountNameInput.text.trim();
    final password = _securePasswordInput.text.trim();

    if (name.isEmpty) {
      StageWhisper.caution('Please enter account name');
      return;
    }

    if (password.isEmpty) {
      StageWhisper.caution('Please enter password');
      return;
    }

    if (password.length < 6) {
      StageWhisper.caution('Password must be at least 6 characters');
      return;
    }

    LoadingCurtain.raiseCurtain(message: 'Creating account...');

    // 使用全局状态管理
    final userRoom = GlobalStateProvider.userRoomOf(context);

    // 执行注册
    final registerSuccess = userRoom.performRegister(
      account: name,
      password: password,
      username: name, // 使用账号名作为用户名
      birthDate: DateTime.now(), // 使用注册日期作为出生日期
      signature: 'Welcome to the lake community!', // 默认签名
      avatar: 'assets/images/avatar1.png', // 默认头像
    );

    await Future.delayed(const Duration(seconds: 1));
    LoadingCurtain.lowerCurtain();

    if (registerSuccess) {
      StageWhisper.cheer('Account created successfully!');

      // 注册成功后返回登录页面，并传递账号密码
      Navigator.of(context).pop({'account': name, 'password': password});
    } else {
      StageWhisper.lament('Account creation failed. Please try again.');
    }
  }

  /// 返回登录页面
  void _returnToLogin() {
    Navigator.of(context).pop();
  }

  /// 打开服务条款
  void _accessTermsOfService() {
    CommonUtils.launchUrl(ProjectConstants.termsOfServiceUrl);
  }

  /// 打开隐私政策
  void _accessPrivacyPolicy() {
    CommonUtils.launchUrl(ProjectConstants.privacyPolicyUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.splashBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _constructTopBar(),

              // Logo 区域
              Expanded(child: Center(child: _constructLogoArea())),

              // 注册表单卡片（固定在底部）
              _constructRegistrationForm(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _constructTopBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _returnToLogin,
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left,
                color: ColorPalette.black,
                size: 30.sp,
              ),
            ),
          ),
          12.w.widthBox,
          Text(ProjectConstants.appName)
              .fontSize(24.sp)
              .textColor(ColorPalette.black)
              .arimo(weight: FontWeight.bold),
        ],
      ),
    );
  }

  /// 构建 Logo 区域
  Widget _constructLogoArea() {
    return Container(
      width: 100.w,
      height: 100.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(24.r),
        border: Border.all(color: ColorPalette.white, width: 5.w),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.blue1.withValues(alpha: 0.3),
            blurRadius: 20,
            spreadRadius: 2,
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(24.r),
        child: Image.asset(AssetManifest.logo, fit: BoxFit.cover),
      ),
    );
  }

  /// 构建注册表单卡片
  Widget _constructRegistrationForm() {
    return Container(
      constraints: BoxConstraints(maxHeight: 600.h),
      padding: EdgeInsets.fromLTRB(24.w, 32.h, 24.w, 24.h),
      decoration: BoxDecoration(
        color: ColorPalette.inputBg,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.black.withValues(alpha: 0.1),
            blurRadius: 20,
            offset: Offset(0, -4.h),
          ),
        ],
      ),
      child: SingleChildScrollView(
        physics: const ClampingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 标题
            Center(
              child: Text('Welcome to join')
                  .fontSize(26.sp)
                  .textColor(ColorPalette.blue1)
                  .arimo(weight: FontWeight.bold),
            ),

            32.h.heightBox,

            // 账户名输入框
            _assembleTextField(
              controller: _accountNameInput,
              label: 'name',
              hintText: 'Enter your account name',
              isPassword: false,
            ),

            20.h.heightBox,

            // 密码输入框
            _assembleTextField(
              controller: _securePasswordInput,
              label: 'password',
              hintText: 'password',
              isPassword: true,
            ),

            20.h.heightBox,

            // 占位：对应登录页面的"Don't have an account?"提示
            SizedBox(height: 16.h),

            24.h.heightBox,

            // 注册按钮
            _assembleRegisterButton(),

            24.h.heightBox,

            // 占位：对应登录页面的"Or continue with"分割线
            SizedBox(height: 16.h),

            24.h.heightBox,

            // 占位：对应登录页面的Apple登录按钮
            SizedBox(height: 60.h),

            24.h.heightBox,

            // 服务条款
            _constructLegalNotice(),
          ],
        ),
      ),
    );
  }

  /// 构建输入框
  Widget _assembleTextField({
    required TextEditingController controller,
    required String label,
    required String hintText,
    required bool isPassword,
  }) {
    return Stack(
      children: [
        Container(
          margin: EdgeInsets.only(top: 8.h),
          decoration: BoxDecoration(
            color: ColorPalette.inputBg,
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: ColorPalette.grey, width: 1),
          ),
          child: TextField(
            controller: controller,
            obscureText: isPassword,
            style: TextStyle(fontSize: 15.sp, color: ColorPalette.black),
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
              hintText: hintText,
              hintStyle: TextStyle(
                fontSize: 15.sp,
                color: ColorPalette.black.withValues(alpha: 0.3),
              ),
              border: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 16.w,
                vertical: 14.h,
              ),
            ),
          ),
        ),
        Positioned(
          left: 12.w,
          top: 0,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 4.w),
            color: ColorPalette.inputBg,
            child:
                Text(label)
                    .fontSize(12.sp)
                    .textColor(ColorPalette.black.withValues(alpha: 0.6))
                    .arimo(),
          ),
        ),
      ],
    );
  }

  /// 构建注册按钮
  Widget _assembleRegisterButton() {
    return Container(
      height: 50.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [ColorPalette.blue1, ColorPalette.blue1],
        ),
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: ColorPalette.blue1.withValues(alpha: 0.3),
            blurRadius: 12,
            offset: Offset(0, 4.h),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: Center(
          child: Text('Register')
              .fontSize(16.sp)
              .textColor(ColorPalette.white)
              .arimo(weight: FontWeight.bold),
        ),
      ),
    ).withTapEffect(onTap: _establishAccount);
  }

  /// 构建服务条款区域
  Widget _constructLegalNotice() {
    return FittedBox(
      fit: BoxFit.scaleDown,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('By Continuing you agree with ')
              .fontSize(11.sp)
              .textColor(ColorPalette.black.withValues(alpha: 0.6)),
          GestureDetector(
            onTap: _accessTermsOfService,
            child: Text(
              'Terms of Service',
              style: TextStyle(
                fontSize: 11.sp,
                color: ColorPalette.black,
                fontWeight: FontWeight.w600,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
          Text(' & ')
              .fontSize(11.sp)
              .textColor(ColorPalette.black.withValues(alpha: 0.6)),
          GestureDetector(
            onTap: _accessPrivacyPolicy,
            child: Text(
              'Privacy Policy',
              style: TextStyle(
                fontSize: 11.sp,
                color: ColorPalette.black,
                fontWeight: FontWeight.w600,
                decoration: TextDecoration.underline,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
